package com.pi.base.controller;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.pi.base.common.BaseResult;
import com.pi.base.constant.SysStatics;
import com.pi.base.entity.SysMenu;
import com.pi.base.service.ISysMenuService;
import com.pi.base.service.ISysRoleService;
import com.pi.base.util.SysAuthUtil;
import com.pi.base.util.ValidUtil;

@Controller
@RequestMapping("/menu")
public class MenuController extends BaseController{
	
	private final Logger logger = LoggerFactory.getLogger(MenuController.class);
	@Resource
	private ISysRoleService sysRoleService;
	@Resource
	private ISysMenuService sysMenuService ;
	
	@RequestMapping(value="/getMenuTreeList")
	@ResponseBody
	public String getMenuTreeList() throws Exception{
		List<SysMenu> menuList = sysMenuService.getMenuListByParentId(SysStatics.MENU_TREE_ROOT);
		List<SysMenu> newList_ = SysAuthUtil.turnListToTreeList(menuList, SysMenu.class, "getParentid", SysStatics.MENU_TREE_ROOT+"", "getId", "getParentid", "setSubList");
		String jsonStr = JSONObject.toJSONString(newList_);
		jsonStr = jsonStr.replaceAll("subList", "children");
		return jsonStr;
	}
	
	@RequestMapping(value="/doMenuRemove")
	@ResponseBody
	public BaseResult doMenuRemove(@RequestParam  Integer removeMenuId) throws Exception{
		return sysMenuService.delParentMenu(removeMenuId);
	}

	@RequestMapping(value="/doMenuAdd")
	@ResponseBody
	public BaseResult doMenuAdd(@ModelAttribute SysMenu newMenu)
			throws Exception {
		logger.debug("addMenu:" + newMenu.toString());
		if (newMenu == null || ValidUtil.isBlank(newMenu.getName())) {
			return BaseResult.newErrorResult("菜单名称不能为空");
		}
		// 如果是新增按钮，验证按钮code是否重复
		if (SysStatics.MENU_BTN_LEVEL == newMenu.getLevel()) {
			int countCode = sysMenuService.countSysMenuByCode(newMenu.getUrl());
			if (countCode > 0) {
				return BaseResult.newErrorResult("按钮code已经存在");
			}
		}
		if (ValidUtil.isBlank(newMenu.getImgurl())) {
			// 默认icon
			if (newMenu.getLevel() < 4) {
				newMenu.setImgurl("ico-2");
			} else {
				newMenu.setImgurl("bico-52");
			}
		}
		sysMenuService.insertSysMenu(newMenu);
		return BaseResult.newSuccessResult("新增成功");
	}
	

}
